package org.dtrd.modules.doctor.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.Constant.DoctorPatientRelationType;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.doctor.entity.bean.DoctorPatientInfo;
import org.dtrd.modules.doctor.entity.request.SearchPatientRequest;
import org.dtrd.modules.doctor.service.IDtrdEntRdDoctorService;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorPatientService;
import org.dtrd.modules.patient.entity.bean.PatientInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_ADD;
import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_QUERY;
import static org.dtrd.config.system.SystemState.ResponseState.STATE_OPERATION_FAILURE;
import static org.dtrd.config.system.SystemState.ResponseState.STATE_PARAMS_MISSING;

/**
 * @author qr
 * @date 2021/12/15 10:42
 */
@Api(tags = "医生和患者关系")
@RestController
@Slf4j
@RequestMapping("/doctor/patient/")
public class DoctorPatientController extends BaseController {

    @Autowired
    private IDtrdEntRdDoctorService doctorService;
    @Autowired
    private IDtrdRlDoctorPatientService dPRlService;
    @Autowired
    private BaseCommonService baseCommonService;


    @ApiOperation(value = "获取某个分组的患者", notes = "1: 在管, 2: 续管, 3: 已完成")
    @GetMapping("group/list")
    public Result<?> listGroupPatient(@RequestParam Integer doctorId,
                                      @RequestParam Integer groupId,
                                      @RequestParam(required = false) Integer page,
                                      @RequestParam(required = false) Integer pageSize) {
        if (isIntParamInvalid(doctorId) || isIntParamInvalid(groupId)) {
            return error(STATE_PARAMS_MISSING);
        }
        page = getIntParam(page, 1);
        pageSize = getPageSize(pageSize, Constant.PAGESIZE);
        IPage<DoctorPatientInfo> list = doctorService.pageGroupPatient(doctorId, groupId, page, pageSize);
        Integer inManageNum = dPRlService.countDoctorGroupPatient(doctorId, Constant.Group.IN_MANAGE.getType());
        Integer continueManageNum = dPRlService.countDoctorGroupPatient(doctorId, Constant.Group.CONTINUE_MANAGE.getType());
        JSONObject jsonObject = new JSONObject();
        if (list == null || CollectionUtil.isEmpty(list.getRecords())) {
            jsonObject.put("recordList", Collections.EMPTY_LIST);
            jsonObject.put("inManageCount", inManageNum);
            jsonObject.put("continueManageCount", continueManageNum);
            jsonObject.put("totalPage", 0);
        } else {
            jsonObject.put("recordList", list.getRecords());
            jsonObject.put("inManageCount", inManageNum);
            jsonObject.put("continueManageCount", continueManageNum);
            jsonObject.put("totalPage", list.getPages());
        }
        String logContent = String.format("获取某个分组的患者，查询医生id：%d, 分组id: %d", doctorId, groupId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(jsonObject);
    }

    @ApiOperation(value = "获取某个服务包状态的患者", notes = "1: 待服务，2: 服务中， 3：已完成")
    @GetMapping("package/list")
    public Result<?> listPackagePatient(@RequestParam Integer doctorId,
                                        @RequestParam Integer status,
                                        @RequestParam(required = false) Integer page,
                                        @RequestParam(required = false) Integer pageSize) {
        if (isIntParamInvalid(doctorId) || isIntParamInvalid(status)) {
            return error(STATE_PARAMS_MISSING);
        }
        page = getIntParam(page, 1);
        pageSize = getPageSize(pageSize, Constant.PAGESIZE);
        IPage<DoctorPatientInfo> list = doctorService.pagePackagePatient(doctorId, status, page, pageSize);
        JSONObject jsonObject = new JSONObject();
        if (list == null || CollectionUtil.isEmpty(list.getRecords())) {
            jsonObject.put("recordList", Collections.EMPTY_LIST);
            jsonObject.put("count", 0);
            jsonObject.put("totalPage", 1);
        } else {
            jsonObject.put("recordList", list.getRecords());
            jsonObject.put("count", list.getTotal());
            jsonObject.put("totalPage", list.getPages());
        }
        String logContent = String.format("获取某个服务包状态的患者，查询医生id：%d, status: %d", doctorId, status);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(jsonObject);
    }

    @ApiOperation("设置医生和患者关系")
    @GetMapping("link")
    public Result<?> addDoctorPatientRelation(@RequestParam("doctorId") Integer doctorId,
                                              @RequestParam("patientId") Integer patientId) {
        if (isIntParamInvalid(doctorId) || isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
//        boolean result = doctorService.addDoctorPatientRelation(doctorId, patientId);
        boolean result = dPRlService.saveOrUpdateDoctorPatientRelation(doctorId, patientId, DoctorPatientRelationType.ADD_BY_OMS.getType());
        String logContent = String.format("设置医生和患者关系，医生id：%d, 患者id: %d", doctorId, patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_ADD);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("搜索患者")
    @PostMapping("get")
    public Result<?> searchPatient(@RequestParam Integer doctorId,
                                   @RequestBody SearchPatientRequest request) {
        if (isIntParamInvalid(doctorId)) {
            return error(STATE_PARAMS_MISSING);
        }
        List<PatientInfo> list = doctorService.searchPatient(doctorId, request);
        String logContent = String.format("医生id: %d, 搜索患者, 搜索条件：%s", doctorId, request);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(list);
    }
}
